<template>
  <div class="scholarship-student">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>奖学金申请（学生）</span>
            </div>
          </template>
          <el-form :model="scholarshipForm" :rules="rules" ref="scholarshipFormRef" label-width="120px">
            <el-form-item label="奖学金类型" prop="type">
              <el-select v-model="scholarshipForm.type" placeholder="请选择奖学金类型">
                <el-option label="国家奖学金" value="1" />
                <el-option label="国家励志奖学金" value="2" />
                <el-option label="校级奖学金" value="3" />
                <el-option label="专业奖学金" value="4" />
              </el-select>
            </el-form-item>
            <el-form-item label="申请学年" prop="academicYear">
              <el-input v-model="scholarshipForm.academicYear" placeholder="如：2023-2024" />
            </el-form-item>
            <el-form-item label="平均绩点" prop="gpa">
              <el-input-number v-model="scholarshipForm.gpa" :min="0" :max="4" :precision="2" />
            </el-form-item>
            <el-form-item label="专业排名" prop="ranking">
              <el-input-number v-model="scholarshipForm.ranking" :min="1" />
            </el-form-item>
            <el-form-item label="获奖情况" prop="awards">
              <el-input v-model="scholarshipForm.awards" type="textarea" :rows="3" placeholder="请列出相关获奖情况" />
            </el-form-item>
            <el-form-item label="社会实践" prop="practice">
              <el-input v-model="scholarshipForm.practice" type="textarea" :rows="3" placeholder="请描述社会实践经历" />
            </el-form-item>
            <el-form-item label="申请理由" prop="reason">
              <el-input v-model="scholarshipForm.reason" type="textarea" :rows="4" placeholder="请详细说明申请理由" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitScholarship" :loading="loading">提交申请</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>申请记录</span>
          </template>
          <template v-if="scholarshipHistory.length > 0">
            <el-timeline>
              <el-timeline-item v-for="(item, index) in scholarshipHistory" :key="index" :timestamp="item.date"
                placement="top">
                <el-card class="history-card" @click="openDetail(item)">
                  <h4>{{ item.type }}</h4>
                  <p>申请学年：{{ item.academicYear }}</p>
                  <el-tag :type="getStatusType(item.status)">{{ getStatusText(item.status) }}</el-tag>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </template>
          <el-empty v-else description="暂无申请记录" />
        </el-card>
      </el-col>
    </el-row>
    <!-- 申请详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="申请详情" width="600px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="申请时间">{{ detailData.createTime || detailData.date }}</el-descriptions-item>
        <el-descriptions-item label="奖学金ID">{{ detailData.id || '-' }}</el-descriptions-item>
        <el-descriptions-item label="学生学号">{{ detailData.studentNum || '-' }}</el-descriptions-item>
        <el-descriptions-item label="学生姓名">{{ detailData.name || '-' }}</el-descriptions-item>
        <el-descriptions-item label="奖学金类型">{{ detailData.type }}</el-descriptions-item>
        <el-descriptions-item label="申请学年">{{ detailData.academicYear }}</el-descriptions-item>
        <el-descriptions-item label="平均绩点">{{ detailData.gpa ?? '-' }}</el-descriptions-item>
        <el-descriptions-item label="专业排名">{{ detailData.ranking ?? '-' }}</el-descriptions-item>
        <el-descriptions-item label="获奖情况">{{ detailData.awards || '-' }}</el-descriptions-item>
        <el-descriptions-item label="社会实践">{{ detailData.practice || '-' }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getStatusType(detailData.status)">{{ getStatusText(detailData.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="绩点核验">
          <el-tag :type="getVerifyTag(detailData.gpaStatus).type">{{ getVerifyTag(detailData.gpaStatus).text }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="违纪核验">
          <el-tag :type="getVerifyTag(detailData.indisciplineStatus).type">{{
            getVerifyTag(detailData.indisciplineStatus).text }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请理由">{{ detailData.reason || '-' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { createScholarship, getScholarshipListByStudentNum, getScholarshipsByScholarshipId, type CreateScholarshipRequest } from '@/api/scholarship'
import { getStudentById } from '@/api/studentInfo'

// 类型定义（Types）
type ScholarshipHistoryItem = {
  id?: string
  date: string
  createTime?: string
  type: string
  academicYear: string
  status: number
  gpaStatus?: number
  indisciplineStatus?: number
  gpa?: number
  ranking?: number
  awards?: string
  practice?: string
  reason?: string
  studentNum?: string
  name?: string
}

// 状态与表单（State）
const scholarshipFormRef = ref<FormInstance>()
const loading = ref(false)
const scholarshipHistory = ref<ScholarshipHistoryItem[]>([])
const detailDialogVisible = ref(false)
const detailData = ref<ScholarshipHistoryItem>({ date: '', type: '', academicYear: '', status: 0 })
const currentStudentNum = ref<string>('')
const currentStudentName = ref<string>('')

const scholarshipForm = reactive({
  type: '',
  academicYear: '',
  gpa: 0,
  ranking: 1,
  awards: '',
  practice: '',
  reason: ''
})

// 表单校验规则（Validation Rules）
const rules: FormRules = {
  type: [{ required: true, message: '请选择奖学金类型', trigger: 'change' }],
  academicYear: [{ required: true, message: '请输入申请学年', trigger: 'blur' }],
  gpa: [{ required: true, message: '请输入平均绩点', trigger: 'blur' }],
  ranking: [{ required: true, message: '请输入专业排名', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入申请理由', trigger: 'blur' }]
}

// API 调用（API Calls）
// 根据学号获取奖学金信息并渲染到历史记录
const loadScholarshipByStudentNum = async () => {
  try {
    loading.value = true
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    // 从用户信息中提取学号
    const res = await getStudentById(userInfo.userId)
    if (res.code === '200') {
      currentStudentNum.value = res.data?.studentNum || ''
      currentStudentName.value = res.data?.name || ''
      // 根据学号查询奖学金历史记录
      const response = await getScholarshipListByStudentNum(currentStudentNum.value)

      if (response.code === '200') {
        const list: Array<any> = response.data || []
        scholarshipHistory.value = list.map(item => ({
          id: String(item.id),
          date: item.createTime || '',
          createTime: item.createTime || '',
          type: getScholarshipType(Number(item.type)),
          academicYear: item.applyYear || '',
          status: Number(item.status),
          gpaStatus: Number(item.gpaStatus ?? -1),
          indisciplineStatus: Number(item.indisciplineStatus ?? -1),
          gpa: Number(item.gpa ?? NaN),
          ranking: Number(item.ranking ?? NaN),
          awards: item.awards || '',
          practice: item.practice || '',
          reason: item.reason || '',
          studentNum: item.studentNum || '',
          name: item.name || ''
        }))
        // console.log('奖学金历史记录:', scholarshipHistory.value)
      } else {
        ElMessage.error(response.msg || '获取奖学金信息失败')
      }
    }
  } catch (error) {
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 提交奖学金申请并触发核验
const submitScholarship = async () => {
  if (!scholarshipFormRef.value) return
  await scholarshipFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        // 构造后端需要的创建申请数据
        const requestData: CreateScholarshipRequest = {
          studentNum: currentStudentNum.value,
          name: currentStudentName.value || '未知',
          ranking: Number(scholarshipForm.ranking),
          type: Number(scholarshipForm.type),
          gpa: Number(scholarshipForm.gpa),
          applyYear: scholarshipForm.academicYear,
          practice: scholarshipForm.practice,
          awards: scholarshipForm.awards,
          reason: scholarshipForm.reason
        }
        // 提交奖学金申请
        const response = await createScholarship(requestData)
        if (response.code === '200') {
          ElMessage.success('申请提交成功')
          // 提交后重置表单
          resetForm()
          await loadScholarshipByStudentNum()

        } else {
          ElMessage.error(response.msg || '提交失败')
        }
      } catch (error) {
        ElMessage.error('提交失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 事件与表单处理（UI Handlers）
const resetForm = () => {
  if (!scholarshipFormRef.value) return
  scholarshipFormRef.value.resetFields()
}

// 工具函数（Utilities）
// 状态映射统一为后端定义：
// 0 未审核, 1 审核中, 2 审批驳回, 3 审批通过
const getStatusType = (status?: number) => {
  switch (status) {
    case 0: return 'warning'
    case 1: return 'info'
    case 2: return 'danger'
    case 3: return 'success'
    default: return 'default'
  }
}

const getStatusText = (status?: number) => {
  switch (status) {
    case 0: return '未审核'
    case 1: return '审核中'
    case 2: return '审批驳回'
    case 3: return '审批通过'
    default: return '未知状态'
  }
}

// 绩点与违纪核验标签：0 未核验, 1 核验通过, 2 核验未通过
const getVerifyTag = (val?: number) => {
  switch (val) {
    case 0: return { type: 'warning', text: '未核验' }
    case 1: return { type: 'success', text: '核验通过' }
    case 2: return { type: 'danger', text: '核验未通过' }
    default: return { type: 'info', text: '未知' }
  }
}

const getScholarshipType = (type?: number) => {
  switch (type) {
    case 1: return '国家奖学金'
    case 2: return '国家励志奖学金'
    case 3: return '校级奖学金'
    case 4: return '专业奖学金'
    default: return '未知类型'
  }
}

// 生命周期（Lifecycle）
onMounted(() => {
  // 页面加载时获取当前用户的奖学金申请记录
  loadScholarshipByStudentNum()
})

// 打开详情对话框并根据奖学金ID获取后端详情填充
const openDetail = async (item: ScholarshipHistoryItem) => {
  // 先显示已有信息，提升响应速度
  detailData.value = { ...item }
  if (item.id !== undefined && item.id !== null) {
    ElMessage.info(`奖学金ID：${item.id}`)
  }
  console.log('正在打开detailData:', detailData.value)
  detailDialogVisible.value = true

  if (!item.id) return
  try {
    const resp = await getScholarshipsByScholarshipId(item.id)
    if (resp.code === '200') {
      const raw = resp.data || []
      const data = Array.isArray(raw) ? raw[0] : raw
      if (data) {
        detailData.value = {
          ...detailData.value,
          id: data.id !== undefined ? String(data.id) : detailData.value.id,
          date: data.createTime || detailData.value.date,
          createTime: data.createTime || detailData.value.createTime,
          // 若后端返回数字类型则转换为中文类型名，否则沿用现有显示值
          type: data.type !== undefined ? getScholarshipType(Number(data.type)) : detailData.value.type,
          academicYear: data.applyYear ?? detailData.value.academicYear,
          status: data.status !== undefined ? Number(data.status) : detailData.value.status,
          gpaStatus: data.gpaStatus !== undefined ? Number(data.gpaStatus) : (detailData.value.gpaStatus ?? -1),
          indisciplineStatus: data.indisciplineStatus !== undefined ? Number(data.indisciplineStatus) : (detailData.value.indisciplineStatus ?? -1),
          gpa: data.gpa !== undefined && !isNaN(Number(data.gpa)) ? Number(data.gpa) : detailData.value.gpa,
          ranking: data.ranking !== undefined && !isNaN(Number(data.ranking)) ? Number(data.ranking) : detailData.value.ranking,
          awards: data.awards ?? detailData.value.awards,
          practice: data.practice ?? detailData.value.practice,
          reason: data.reason ?? detailData.value.reason,
          studentNum: data.studentNum ?? detailData.value.studentNum,
          name: data.name ?? detailData.value.name
        }
      }
    } else {
      ElMessage.warning(resp.msg || '获取申请详情失败')
    }
  } catch (_) {
    ElMessage.error('获取申请详情失败，请稍后重试')
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>